package com.markerhub.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.markerhub.common.dto.LoginDto;
import com.markerhub.common.dto.RegisterDto;
import com.markerhub.common.dto.ResetPasswordDto;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.User;
import com.markerhub.service.UserService;
import com.markerhub.util.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@RestController
public class AccountController {

    @Autowired
    UserService userService;

    @Autowired
    JwtUtils jwtUtils;
    @GetMapping("/hi")
    public Result hi(){
        return Result.succ("hi");
    }
    @RequiresAuthentication
    @GetMapping("/index")
    public Object index(){
        User user = userService.getById(1L);
        return Result.succ(user);

    }



    @PostMapping("/resetpassword")
    public Result resetPassword(@RequestBody @Valid ResetPasswordDto resetPasswordDto) {
        // 根据用户名查找用户
        User user = userService.getOne(new QueryWrapper<User>().eq("username", resetPasswordDto.getUsername()));
        if (user == null) {
            return Result.fail("用户不存在");
        }

        // 设置新密码
        user.setPassword(SecureUtil.md5(resetPasswordDto.getPassword()));

        // 调用 IService 提供的 updateById 方法更新用户信息
        if (userService.updateById(user)) {
            return Result.succ("密码重置成功");
        } else {
            return Result.fail("密码重置失败");
        }
    }



    @PostMapping("/register")
    public Result register(@RequestBody @Valid RegisterDto registerDto) {
        // 创建用户对象
        User user = new User();
        user.setUsername(registerDto.getUsername());
        user.setPassword(SecureUtil.md5(registerDto.getPassword()));
        user.setAvatar("https://i.pravatar.cc/150?img=1"); // 设置默认头像
        user.setRole("user"); // 设置默认角色
        user.setStatus(1); // 设置默认状态为启用
        // 调用注册方法
        try {
            userService.register(user);
            return Result.succ("注册成功");
        } catch (RuntimeException e) {
            return Result.fail(e.getMessage());
        }
    }

    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {

        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        Assert.notNull(user, "用户不存在");

        if(!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
            return Result.fail("密码不正确");
        }
        String jwt = jwtUtils.generateToken(user.getId());

        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");

        return Result.succ(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("realName", user.getRealName())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .put("role",user.getRole())
                .put("role", user.getRole().toLowerCase())
                .put("token", jwt)
                .put("status",user.getStatus())
                .put("phone",user.getPhone())
                .put("sex",user.getSex())
                .put("birthday",user.getBirthday())
                .map()
        );
    }

    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.succ(null);
    }

}
